<template>
  <Layout>
    <div class="category-container">
      <!-- 功能入口区域 -->
      <div class="function-area">
        <div>
          <el-button type="primary" @click="handleCreateCategory">新建分组</el-button>
          <el-button type="info" @click="debugTableData">调试数据</el-button>
        </div>
        <div class="search-box">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入内容"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </div>
      </div>

      <!-- 数据列表 -->
      <div class="data-table">
        <el-table
          :data="categoryList"
          style="width: 100%"
          v-loading="loading"
          border
          row-key="objectId"
          :indent="20"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          default-expand-all
        >
          <el-table-column prop="name" label="分组名称" width="200">
            <template #default="scope">
              <span>
                {{ scope.row.name }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="层级" width="120">
            <template #default="scope">
              <el-tag v-if="scope.row.level === 1" size="small" type="primary">一级分组</el-tag>
              <el-tag v-else-if="scope.row.level === 2" size="small" type="success">二级分组</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="sort" label="排序" width="80" />
          <el-table-column prop="createdAt" label="创建时间" width="180" />
          <el-table-column label="操作" width="250" fixed="right">
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                @click="handleAddSubCategory(scope.row)"
                v-if="scope.row.level < 2"
              >
                新增二级分组
              </el-button>
              <el-button
                link
                type="primary"
                size="small"
                @click="handleEdit(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                link
                type="danger"
                size="small"
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- 新建/编辑分组弹窗 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="500px"
        center
      >
        <el-form
          ref="formRef"
          :model="categoryForm"
          :rules="formRules"
          label-width="80px"
        >
          <el-form-item label="分组名称" prop="name">
            <el-input v-model="categoryForm.name" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="分组描述" prop="description">
            <el-input v-model="categoryForm.description" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input-number v-model="categoryForm.sort" :min="1" :max="999" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确认</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </Layout>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import Layout from '@/components/Layout.vue';
import { getCategoryList, createCategory, updateCategory, deleteCategory } from '@/api/category';

// 加载状态
const loading = ref(false);

// 分类列表数据
const categoryList = ref<any[]>([]);
const allCategories = ref<any[]>([]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 搜索关键字
const searchKeyword = ref('');

// 弹窗相关
const dialogVisible = ref(false);
const dialogMode = ref<'create' | 'edit' | 'createSub'>('create');
const formRef = ref();

// 弹窗标题
const dialogTitle = computed(() => {
  switch (dialogMode.value) {
    case 'create':
      return '新增分组';
    case 'edit':
      return '编辑分组';
    case 'createSub':
      return '新增二级分组';
    default:
      return '分组信息';
  }
});

// 分类表单
const categoryForm = reactive({
  objectId: '',
  name: '',
  parentIdas: '',
  level: 1,
  description: '',
  sort: 1,
  isShow: true
});

// 表单校验规则
const formRules = {
  name: [
    { required: true, message: '请输入分组名称', trigger: 'blur' },
    { max: 50, message: '分组名称不能超过50个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ]
};

// 加载分类列表
const loadCategoryList = async () => {
  loading.value = true;
  try {
    const response: any = await getCategoryList();
    console.log('原始分类数据:', JSON.stringify(response)); // 打印完整的原始数据
    
    // 直接使用response，不再尝试访问response.data
    allCategories.value = response.results || [];
    
    // 处理树形结构
    console.log('分类数据结构:', JSON.stringify(allCategories.value)); // 打印完整的分类数据
    
    // 检查每个分类的parentIdas字段
    allCategories.value.forEach(item => {
      console.log(`分类 ${item.name} (${item.objectId}) 的 parentIdas:`, item.parentIdas, typeof item.parentIdas);
      // 确保level字段存在
      if (!item.level) {
        item.level = item.parentIdas ? 2 : 1;
      }
    });
    
    // 手动构建树形结构
    interface CategoryItem {
      objectId: string;
      name: string;
      level?: number;
      parentIdas?: string;
      description?: string;
      sort?: number;
      createdAt?: string;
      children?: CategoryItem[];
      [key: string]: any;
    }
    
    // 创建一个新的数组来存储处理后的数据
    let processedData: any[] = [];
    
    // 先找出所有一级分类（没有parentIdas的）
    const rootCategories = allCategories.value.filter(item => !item.parentIdas);
    
    // 然后找出所有二级分类（有parentIdas的）
    const subCategories = allCategories.value.filter(item => item.parentIdas);
    
    console.log(`找到 ${rootCategories.length} 个一级分类和 ${subCategories.length} 个二级分类`);
    
    // 处理每个一级分类
    rootCategories.forEach(root => {
      // 创建一个新对象，避免引用原始对象
      const rootItem: CategoryItem = { ...root, children: [] };
      
      // 查找该一级分类下的所有二级分类
      const children = subCategories.filter((sub: any) => sub.parentIdas === root.objectId);
      
      if (children.length > 0) {
        // 将二级分类添加到一级分类的children数组中
        rootItem.children = children.map((child: any) => ({ ...child }));
        console.log(`为一级分类 ${root.name} 添加了 ${children.length} 个二级分类`);
      }
      
      // 将处理后的一级分类添加到结果数组中
      processedData.push(rootItem);
    });
    
    // 搜索过滤
    if (searchKeyword.value.trim()) {
      const keyword = searchKeyword.value.toLowerCase();
      processedData = processedData.filter(item => {
        // 检查一级分类名称
        const rootMatch = item.name.toLowerCase().includes(keyword);
        // 检查二级分类名称
        const childrenMatch = item.children?.some((child: any) => 
          child.name.toLowerCase().includes(keyword)
        );
        return rootMatch || childrenMatch;
      });
    }
    
    console.log('处理后的数据:', JSON.stringify(processedData));
    
    // 计算总数（包括所有一级分类和二级分类）
    total.value = processedData.reduce((sum, item) => {
      return sum + 1 + (item.children?.length || 0);
    }, 0);
    
    // 分页处理
    const startIndex = (currentPage.value - 1) * pageSize.value;
    const endIndex = startIndex + pageSize.value;
    
    // 将树形结构扁平化进行分页
    const flattenedData: any[] = [];
    processedData.forEach((item: any) => {
      // 添加一级分类
      flattenedData.push({ ...item, children: [] });
      // 添加二级分类
      if (item.children && item.children.length > 0) {
        item.children.forEach((child: any) => {
          flattenedData.push(child);
        });
      }
    });
    
    // 应用分页
    const paginatedData = flattenedData.slice(startIndex, endIndex);
    
    // 重新构建树形结构用于显示
    const displayData: any[] = [];
    const processedIds = new Set();
    
    paginatedData.forEach((item: any) => {
      if (!processedIds.has(item.objectId)) {
        if (!item.parentIdas) {
          // 这是一级分类
          const rootItem: any = { ...item, children: [] };
          // 查找该一级分类下的二级分类（在当前分页数据中）
          const children = paginatedData.filter((child: any) => 
            child.parentIdas === item.objectId && child.objectId !== item.objectId
          );
          if (children.length > 0) {
            rootItem.children = children;
          }
          displayData.push(rootItem);
          processedIds.add(item.objectId);
          children.forEach((child: any) => processedIds.add(child.objectId));
        } else {
          // 这是二级分类，检查父分类是否已处理
          const parent = paginatedData.find((p: any) => p.objectId === item.parentIdas);
          if (!parent || !processedIds.has(parent.objectId)) {
            // 父分类不在当前分页中，单独显示这个二级分类
            displayData.push(item);
            processedIds.add(item.objectId);
          }
        }
      }
    });
    
    // 将处理后的数据赋值给categoryList
    categoryList.value = displayData;
    
    // 强制更新表格
    nextTick(() => {
      console.log('表格数据已更新:', categoryList.value);
    });
  } catch (error) {
    console.error('获取分类列表失败:', error);
    ElMessage.error('获取分类列表失败');
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  loadCategoryList();
};

// 处理页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  loadCategoryList();
};

// 处理每页条数变化
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  loadCategoryList();
};

// 处理新建分类
const handleCreateCategory = () => {
  dialogMode.value = 'create';
  resetForm();
  categoryForm.parentIdas = '';
  dialogVisible.value = true;
};

// 处理添加子分类
const handleAddSubCategory = (row: any) => {
  dialogMode.value = 'createSub';
  resetForm();
  categoryForm.parentIdas = row.objectId;
  dialogVisible.value = true;
};

// 处理编辑
const handleEdit = (row: any) => {
  dialogMode.value = 'edit';
  resetForm();
  
  // 填充表单数据
  categoryForm.objectId = row.objectId;
  categoryForm.name = row.name;
  
  // 直接使用字符串类型的parentIdas
  categoryForm.parentIdas = row.parentIdas || '';
  
  categoryForm.level = row.level || 1;
  categoryForm.description = row.description || '';
  categoryForm.sort = row.sort || 1;
  categoryForm.isShow = row.isShow !== false;
  
  dialogVisible.value = true;
};

// 处理删除
const handleDelete = (row: any) => {
  // 检查是否有子分类，直接比较parentIdas
  const hasChildren = allCategories.value.some(item => item.parentIdas === row.objectId);
  
  if (hasChildren) {
    ElMessage.warning('该分类下有子分类，请先删除子分类');
    return;
  }
  
  ElMessageBox.confirm('确定要删除该分类吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteCategory(row.objectId);
      ElMessage.success('删除成功');
      loadCategoryList();
    } catch (error) {
      console.error('删除分类失败:', error);
      ElMessage.error('删除分类失败');
    }
  }).catch(() => {});
};

// 重置表单
const resetForm = () => {
  categoryForm.objectId = '';
  categoryForm.name = '';
  categoryForm.parentIdas = '';
  categoryForm.description = '';
  categoryForm.sort = 1;
  categoryForm.isShow = true;
  
  // 根据对话框模式设置不同的level默认值
  if (dialogMode.value === 'createSub') {
    categoryForm.level = 2;
  } else {
    categoryForm.level = 1;
  }
  
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 确保在createSub模式下level值为2
        if (dialogMode.value === 'createSub') {
          categoryForm.level = 2;
        } else if (dialogMode.value === 'create') {
          categoryForm.level = 1;
        }
        
        // 构建基础数据
        const data: any = {
          name: categoryForm.name,
          level: categoryForm.level,
          description: categoryForm.description,
          sort: categoryForm.sort,
          isShow: categoryForm.isShow
        };
        
        // 处理parentIdas，直接使用字符串，不再转换为Pointer对象
        if (categoryForm.parentIdas) {
          data.parentIdas = categoryForm.parentIdas;
          console.log(`设置parentIdas为: ${data.parentIdas}`);
        } else {
          data.parentIdas = null;
        }
        
        console.log('提交的数据:', data); // 添加日志，查看提交的数据结构
        
        if (dialogMode.value === 'edit') {
          await updateCategory(categoryForm.objectId, data);
          ElMessage.success('编辑成功');
        } else {
          await createCategory(data);
          ElMessage.success('新增成功');
        }
        
        dialogVisible.value = false;
        loadCategoryList();
      } catch (error) {
        console.error('保存分类失败:', error);
        ElMessage.error('保存分类失败');
      }
    }
  });
};

// 页面加载时获取数据
onMounted(() => {
  loadCategoryList();
});

// 监听分类列表变化
watch(categoryList, (newVal) => {
  console.log('分类列表已更新:', newVal);
  checkTreeStructure();
}, { deep: true });

// 检查树形结构
const checkTreeStructure = () => {
  console.log('检查树形结构:');
  categoryList.value.forEach(category => {
    console.log(`分类: ${category.name}, ID: ${category.objectId}, 子分类数量: ${category.children?.length || 0}`);
    if (category.children && category.children.length > 0) {
      category.children.forEach((child: any) => {
        console.log(`  子分类: ${child.name}, ID: ${child.objectId}, 父ID: ${child.parentIdas}`);
      });
    }
  });
};

// 调试表格数据
const debugTableData = () => {
  console.log('当前表格数据:', JSON.stringify(categoryList.value));
  console.log('是否有二级分组:', categoryList.value.some(item => item.children && item.children.length > 0));
  
  // 检查每个分类的children属性
  categoryList.value.forEach(item => {
    console.log(`分类 ${item.name} (${item.objectId}) 的 children:`, item.children);
    if (item.children && item.children.length > 0) {
      console.log(`  有 ${item.children.length} 个子分类`);
      item.children.forEach((child: any) => {
        console.log(`  子分类: ${child.name} (${child.objectId}), parentIdas: ${child.parentIdas}`);
      });
    }
  });
  
  // 检查原始数据
  console.log('原始数据中的二级分类:');
  const subCategories = allCategories.value.filter(item => item.parentIdas);
  subCategories.forEach(item => {
    console.log(`  二级分类: ${item.name} (${item.objectId}), parentIdas: ${item.parentIdas}`);
    
    // 查找对应的父分类
    const parent = allCategories.value.find(p => p.objectId === item.parentIdas);
    if (parent) {
      console.log(`    父分类: ${parent.name} (${parent.objectId})`);
    } else {
      console.log(`    找不到父分类 (${item.parentIdas})`);
    }
  });
  
  // 重新加载数据
  loadCategoryList();
};
</script>

<style scoped>
.category-container {
  padding: 0;
}

.function-area {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-box {
  width: 300px;
}

.data-table {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.expand-detail {
  padding: 10px 20px;
  background-color: #f9f9f9;
}

.level-tag {
  margin-right: 5px;
}

/* 添加树形表格样式 */
:deep(.el-table__row) {
  font-size: 14px;
}

:deep(.el-table__expand-icon) {
  color: #409EFF;
  font-size: 16px;
}

:deep(.el-table__indent) {
  padding-left: 10px;
}

:deep(.el-table__placeholder) {
  display: inline-block;
  width: 20px;
}

/* 强制显示树形结构 */
:deep(.el-table__expand-icon--expanded) {
  transform: rotate(90deg);
}

:deep(.el-table__expand-icon .el-icon) {
  font-size: 12px;
}

:deep(.el-table .el-table__row--level-1) {
  background-color: #f5f7fa;
}
</style> 